package edu.gatech.gro.model.parser;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import edu.gatech.gro.model.NamedList;

public class NamedListJsonHandler extends JsonHandler {

	private static final String TAG = "NAMED_LIST_JSON_HANDLER";

	@Override
	protected void parseDataArray() {
		try {
			getResponse().setData(getNamedLists(json.getJSONArray("data")));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
	}

	@Override
	protected void parseData() {
		NamedList dataParsed = null;
		try {
			dataParsed = getNamedList(json.getJSONObject("data"));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		getResponse().setData(dataParsed);
	}

	public static ArrayList<NamedList> getNamedLists(JSONArray array) {
		ArrayList<NamedList> dataParsed = new ArrayList<NamedList>();
		if (array != null) {
			try {
				for (int i = 0; i < array.length(); i++) {
					dataParsed.add(getNamedList(array.getJSONObject(i)));
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return dataParsed;
	}

	public static NamedList getNamedList(JSONObject obj) {
		NamedList nl = new NamedList();
		try {
			parseAbstractObject(nl, obj);
			nl.setUserId(obj.getInt("userId"));
			nl.setName(obj.getString("name"));
			nl.setNameClean(obj.getString("nameClean"));
			if (obj.has("groups")) {
				nl.setItemGroups(ListGroupListItemJsonHandler.getListGroups(obj.getJSONArray("groups")));
			}
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		return nl;
	}
}
